import 'package:flutter/material.dart';
import 'package:netflix_social/constants/app_constants.dart';
import 'package:netflix_social/models/video.dart';
import 'package:netflix_social/providers/video_provider.dart';
import 'package:netflix_social/theme/app_theme.dart';
import 'package:provider/provider.dart';

class SearchScreen extends StatefulWidget {
  const SearchScreen({Key? key}) : super(key: key);

  @override
  State<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';
  bool _isSearching = false;
  List<String> _searchHistory = [];
  List<String> _popularSearches = [
    '热门电影',
    '科幻电影',
    '动作片',
    '悬疑剧',
    '爱情片',
    '韩剧',
    '动漫',
  ];

  @override
  void initState() {
    super.initState();
    _loadSearchHistory();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadSearchHistory() async {
    // 实际项目中，这里应该从本地存储中加载搜索历史
    setState(() {
      _searchHistory = [
        '我的世界',
        '黑镜',
        '流浪地球',
        '速度与激情',
        '三体',
      ];
    });
  }

  Future<void> _saveSearchQuery(String query) async {
    if (query.trim().isEmpty) return;

    // 更新搜索历史
    setState(() {
      // 如果已存在相同的搜索词，先移除它
      _searchHistory.remove(query);
      // 将新的搜索词添加到最前面
      _searchHistory.insert(0, query);
      // 只保留最近的10条搜索记录
      if (_searchHistory.length > 10) {
        _searchHistory = _searchHistory.sublist(0, 10);
      }
    });

    // 实际项目中，这里应该将搜索历史保存到本地存储
  }

  void _onSearch(String query) {
    if (query.trim().isEmpty) return;

    setState(() {
      _searchQuery = query;
      _isSearching = true;
    });

    _saveSearchQuery(query);

    // 执行搜索
    final videoProvider = Provider.of<VideoProvider>(context, listen: false);
    videoProvider.searchVideos(query);
  }

  void _clearSearchHistory() {
    setState(() {
      _searchHistory = [];
    });
    // 实际项目中，这里应该清除本地存储中的搜索历史
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      appBar: AppBar(
        backgroundColor: AppTheme.backgroundColor,
        elevation: 0,
        title: TextField(
          controller: _searchController,
          autofocus: true,
          style: const TextStyle(color: Colors.white),
          decoration: InputDecoration(
            hintText: '搜索影片、演员、导演...',
            hintStyle: TextStyle(color: Colors.grey[400]),
            border: InputBorder.none,
            prefixIcon: const Icon(Icons.search, color: Colors.grey),
            suffixIcon: _searchController.text.isNotEmpty
                ? IconButton(
                    icon: const Icon(Icons.clear, color: Colors.grey),
                    onPressed: () {
                      _searchController.clear();
                      setState(() {
                        _searchQuery = '';
                        _isSearching = false;
                      });
                    },
                  )
                : null,
          ),
          onChanged: (value) {
            setState(() {
              if (value.isEmpty) {
                _isSearching = false;
              }
            });
          },
          onSubmitted: _onSearch,
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: _isSearching
          ? _buildSearchResults()
          : _searchHistory.isEmpty && _popularSearches.isEmpty
              ? _buildEmptyState()
              : _buildSearchSuggestions(),
    );
  }

  Widget _buildSearchResults() {
    return Consumer<VideoProvider>(
      builder: (context, videoProvider, child) {
        if (videoProvider.isSearching) {
          return const Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(AppTheme.netflixRed),
            ),
          );
        }

        final searchResults = videoProvider.searchResults;

        if (searchResults.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.search_off,
                  size: 70,
                  color: Colors.grey[700],
                ),
                const SizedBox(height: 16),
                Text(
                  '未找到相关内容',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        color: Colors.grey[400],
                      ),
                ),
                const SizedBox(height: 8),
                Text(
                  '请尝试使用其他关键词搜索',
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Colors.grey[600],
                      ),
                ),
              ],
            ),
          );
        }

        return GridView.builder(
          padding: const EdgeInsets.all(16),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 0.7,
            crossAxisSpacing: 12,
            mainAxisSpacing: 16,
          ),
          itemCount: searchResults.length,
          itemBuilder: (context, index) {
            return _buildVideoItem(searchResults[index]);
          },
        );
      },
    );
  }

  Widget _buildSearchSuggestions() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 搜索历史
          if (_searchHistory.isNotEmpty) ...[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '搜索历史',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                TextButton(
                  onPressed: _clearSearchHistory,
                  child: const Text('清除'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _searchHistory
                  .map((item) => _buildSearchChip(
                        item,
                        onTap: () {
                          _searchController.text = item;
                          _onSearch(item);
                        },
                      ))
                  .toList(),
            ),
            const SizedBox(height: 24),
          ],

          // 热门搜索
          if (_popularSearches.isNotEmpty) ...[
            Text(
              '热门搜索',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _popularSearches
                  .map((item) => _buildSearchChip(
                        item,
                        isPopular: true,
                        onTap: () {
                          _searchController.text = item;
                          _onSearch(item);
                        },
                      ))
                  .toList(),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildSearchChip(
    String label, {
    bool isPopular = false,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: isPopular ? AppTheme.netflixRed.withOpacity(0.2) : Colors.grey[800],
          borderRadius: BorderRadius.circular(20),
          border: isPopular
              ? Border.all(color: AppTheme.netflixRed.withOpacity(0.5))
              : null,
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (isPopular) ...[
              Icon(
                Icons.trending_up,
                size: 16,
                color: AppTheme.netflixRed,
              ),
              const SizedBox(width: 4),
            ] else ...[
              Icon(
                Icons.history,
                size: 16,
                color: Colors.grey[400],
              ),
              const SizedBox(width: 4),
            ],
            Text(
              label,
              style: TextStyle(
                color: isPopular ? AppTheme.netflixRed : Colors.grey[300],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVideoItem(Video video) {
    return InkWell(
      onTap: () {
        Navigator.pushNamed(
          context,
          AppConstants.videoDetailRoute,
          arguments: video.id,
        );
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 缩略图
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: NetworkImage(video.thumbnailUrl),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          const SizedBox(height: 8),
          // 标题
          Text(
            video.title,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          const SizedBox(height: 4),
          // 类别和年份
          Text(
            '${video.category} • ${video.year}',
            style: TextStyle(
              color: Colors.grey[500],
              fontSize: 12,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search,
            size: 70,
            color: Colors.grey[700],
          ),
          const SizedBox(height: 16),
          Text(
            '搜索你喜欢的内容',
            style: Theme.of(context).textTheme.titleLarge?.copyWith(
                  color: Colors.grey[400],
                ),
          ),
          const SizedBox(height: 8),
          Text(
            '影片、演员、导演...',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: Colors.grey[600],
                ),
          ),
        ],
      ),
    );
  }
}
